﻿using MediatR;
using SheepCultivation.Common.Domain.main;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;
using System.Linq;

namespace SheepCultivation.API.AddliCation.BreedingD
{
    public class BodySeachHandler : IRequestHandler<BodySeachCommon, Result>
    {
        #region 仓储
        /// <summary>
        /// 品种仓储
        /// </summary>
        public readonly IBaseRepository<Sheepvariety> SheepvarietyRepository;
        /// <summary>
        /// 羊只称重仓储
        /// </summary>
        public readonly IBaseRepository<SheepWeighed> SheepWeighedRepository;
        /// <summary>
        /// 耳号仓储
        /// </summary>
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        public readonly IBaseRepository<Building> BuildingRepository;
        /// <summary>
        /// 栋舍类型仓储
        /// </summary>
        public readonly IBaseRepository<BuildingType> BuildingTypeRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        public readonly IBaseRepository<Columns> ColumnsRepository;
        /// <summary>
        /// 体尺测定仓储
        /// </summary>
        public readonly IBaseRepository<Body> BodyRepository;
        /// <summary>
        /// 首次妊检提示仓储
        /// </summary>
        public readonly IBaseRepository<Pregnancy> PregnancyRepository;
        /// <summary>
        /// 日志
        /// </summary>
        public readonly ILogger<BodyCreateHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sheepvarietyRepository">品种</param>
        /// <param name="SheepWeighedRepository">羊只称重</param>
        /// <param name="BasicInformationRepository"></param>
        /// <param name="BuildingRepository">耳号</param>
        /// <param name="BuildingTypeRepository">栋舍</param>
        /// <param name="ColumnsRepository">栋舍类型</param>
        /// <param name="BodyRepository">体尺测定</param>
        /// <param name="logger">日志</param>
        public BodySeachHandler(IBaseRepository<Sheepvariety> sheepvarietyRepository, IBaseRepository<SheepWeighed> SheepWeighedRepository, IBaseRepository<BasicInformation> BasicInformationRepository, IBaseRepository<Building> BuildingRepository, IBaseRepository<BuildingType> BuildingTypeRepository, IBaseRepository<Columns> ColumnsRepository, IBaseRepository<Body> BodyRepository, IBaseRepository<Pregnancy> PregnancyRepository, ILogger<BodyCreateHandler> logger)
        {
            this.SheepvarietyRepository = sheepvarietyRepository;
            this.SheepWeighedRepository = SheepWeighedRepository;
            this.BasicInformationRepository = BasicInformationRepository;
            this.BuildingRepository = BuildingRepository;
            this.BuildingTypeRepository = BuildingTypeRepository;
            this.ColumnsRepository = ColumnsRepository;
            this.BodyRepository = BodyRepository;
            this.PregnancyRepository = PregnancyRepository;
            this.logger = logger;
        }

        #endregion

        #region 体尺测定显示
        /// <summary>
        /// 体尺测定显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(BodySeachCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            //异常处理
            try
            {
                logger.LogInformation("体尺测定显示成功!");
                var data = new pagesDto();
                var list = (from a in BodyRepository.GetAll()
                            join b in BasicInformationRepository.GetAll() on a.EarsId equals b.BreedingSheepArchiveId
                            join c in PregnancyRepository.GetAll() on b.BreedingSheepArchiveId equals c.BreedingSheepArchiveId
                            join d in ColumnsRepository.GetAll() on c.ColumnsId equals d.ColumnsId
                            join e in BuildingRepository.GetAll() on c.BuildingId equals e.BuildingId
                            join f in SheepvarietyRepository.GetAll() on b.SheepTypeId equals f.SheepvarietyId
                            select new BodyDto()
                            {
                                BodyId = a.BodyId,
                                BodyDaysAge = a.BodyDaysAge,
                                BodyDate = a.BodyDate,
                                BodyHeight = a.BodyHeight,
                                BodyLong = a.BodyLong,
                                BodyShort = a.BodyShort,
                                BodyPipe = a.BodyPipe,
                                BodyScrotal = a.BodyScrotal,
                                BodyBackfat = a.BodyBackfat,
                                BodyEye = a.BodyEye,
                                BodyEyeWeight = a.BodyEyeWeight,
                                SheepSex = b.SheepSex,
                                BreedingSheepArchiveId = b.BreedingSheepArchiveId,
                                Auricle = b.Auricle,
                                PregnancyId=c.PregnancyId,
                                ColumnsId = d.ColumnsId,
                                ColumnsName = d.ColumnsName,
                                BuildingId = e.BuildingId,
                                BuildingName = e.BuildingName,
                                SheepvarietyId = f.SheepvarietyId,
                                SheepvarietyName = f.SheepvarietyName,
                            }).ToList();

                //查询条件：耳号 品种 性别
                if (!string.IsNullOrEmpty(request.auricle))
                {
                    list = list.Where(x => x.Auricle.Contains(request.auricle)).ToList();
                }
                if (request.sheepvarietyId > 0)
                {
                    list = list.Where(x => x.SheepvarietyId == request.sheepvarietyId).ToList();
                }
                if (request.sheepSex > 0)
                {
                    list = list.Where(x => x.SheepSex == request.sheepSex).ToList();
                }

                //分页
                data.totalCount = list.Count();
                data.pageCount = (int)((list.Count() * 1.0) / request.pageSize);
                data.data = list.OrderBy(x => x.BodyId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Code = (int)CommonEnumCode.success;
                result.Data = data;
                result.Msg = "体尺测定显示成功";
            }
            catch (Exception ex)
            {
                logger.LogError("体尺测定显示失败!" + ex.Message);
                result.Msg = "体尺测定显示失败";
            }
            return result;
        }
        #endregion
    }

    /// <summary>
    /// 分页
    /// </summary>
    public class pagesDto
    {
        public int totalCount { get; set; }
        public int pageCount { get; set; }
        public List<BodyDto> data { get; set; }
    }

    /// <summary>
    /// 体尺测定Dto
    /// </summary>
    public class BodyDto()
    {
        /// <summary>
        /// 体尺测定Id
        /// </summary>
        public int BodyId { get; set; }

        /// <summary>
        /// 羊只耳号Id（羊只耳号表 Ears）
        /// </summary>
        public int EarsId { get; set; }
        /// <summary>
        /// 测定日龄
        /// </summary>
        public int BodyDaysAge { get; set; }
        /// <summary>
        /// 测定日期
        /// </summary>
        public DateTime BodyDate { get; set; }
        /// <summary>
        /// 身高(cm)
        /// </summary>
        public decimal BodyHeight { get; set; }
        /// <summary>
        /// 体长(cm)
        /// </summary>
        public decimal BodyLong { get; set; }
        /// <summary>
        /// 胸围(cm)
        /// </summary>
        public decimal BodyShort { get; set; }
        /// <summary>
        /// 管围(cm)
        /// </summary>
        public decimal BodyPipe { get; set; }
        /// <summary>
        /// 阴囊围(cm)
        /// </summary>
        public decimal BodyScrotal { get; set; }
        /// <summary>
        /// 背膘厚度(mm)
        /// </summary>
        public decimal BodyBackfat { get; set; }
        /// <summary>
        /// 眼肌面积(c㎡)
        /// </summary>
        public decimal BodyEye { get; set; }
        /// <summary>
        /// 眼肌宽度(cm)
        /// </summary>
        public decimal BodyEyeWeight { get; set; }
        /// <summary>
        /// 栏位Id
        /// </summary>
        public int ColumnsId { get; set; }
        /// <summary>
        /// 栋舍Id
        /// </summary>
        public int BuildingId { get; set; }
        /// <summary>
        /// 栏位名称
        /// </summary>
        public string? ColumnsName { get; set; }
        /// <summary>
        /// 栋舍名称
        /// </summary>
        public string? BuildingName { get; set; }
        /// <summary>
        /// 品种Id
        /// </summary>
        public int SheepvarietyId { get; set; }
        /// <summary>
        /// 品种名称
        /// </summary>
        public string? SheepvarietyName { get; set; }
        public int BreedingSheepArchiveId { get; set; }
        /// <summary> 
        /// 耳号
        /// </summary>
        public string Auricle { get; set; }
        public int SheepSex { get; set; }
        public int PregnancyId { get; set; }
    }
}
